﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace SZipHandler
{
    public class FileHelper
    {
        public string[] GetFiles(string downloadPath, string[] files)
        {
            var resultList = new List<string>();

            if(files.Length <= 0)
                return resultList.ToArray();

            var rootDir = new DirectoryInfo(downloadPath);
            var downloadDir = string.Empty;

            var findRootFile = Path.Combine(rootDir.FullName, files[0]);
            if (File.Exists(findRootFile))
                downloadDir = rootDir.FullName;
            else
            {
                foreach (var dir in rootDir.GetDirectories())
                {
                    var findFile = Path.Combine(dir.FullName, files[0]);
                    if (File.Exists(findFile))
                    {
                        downloadDir = dir.FullName;
                        break;
                    }
                }
            }

            if(string.IsNullOrEmpty(downloadDir))
                return resultList.ToArray();

            foreach (var file in files)
        	{
                var fullFileName = Path.Combine(downloadDir, file);

                if(File.Exists(fullFileName))
                    resultList.Add(fullFileName);
        	}

            return resultList.ToArray();
        }

        public string[] GetFilesFromArray(string[] fileNames, string[] extensions)
        {
            var resultList = new List<string>();

            if (fileNames.Length <= 0)
                return resultList.ToArray();

            foreach (string extension in extensions)
            {
                var files = fileNames.Where(x => x.EndsWith(extension.Trim(), StringComparison.InvariantCultureIgnoreCase));

                resultList.AddRange(files);
            }

            return resultList.ToArray();
        }

        public string GetSubFolderForExtract(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return null;

            var fileInfo = new FileInfo(fileName);
            
            var name = fileInfo.Name;

            var folder = Path.Combine(fileInfo.DirectoryName, name.Substring(0, name.Length - fileInfo.Extension.Length));
            return folder;
        }
        
    }
}
